package appinfo.controller;

import appinfo.pojo.*;
import appinfo.pojo.vo.AppSearchVo;
import appinfo.service.AppCategoryService;
import appinfo.service.AppInfoService;
import appinfo.service.AppVersionService;
import appinfo.service.DataDictionaryService;
import appinfo.util.EmptyUtils;
import appinfo.util.PageBean;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@Controller
@RequestMapping("/dev/flatform/app")
public class AppinfoController {

    @Resource
    private AppInfoService appInfoService;
    @Resource
    private DataDictionaryService dataDictionaryService;
    @Resource
    private AppCategoryService appCategoryService;
    @Resource
    private AppVersionService appVersionService;

    /**
     * 查看详细 appinfo 信息
     * @param id
     * @return
     */
    @RequestMapping("/appview/{id}")
    public String findAppViewById(@PathVariable Integer id, HttpServletRequest request){
        AppInfo appInfo = appInfoService.findAppViewById(id);
        request.setAttribute("appInfo",appInfo);
        List<AppVersion> appVersionList = appVersionService.findAppVersionPage(id);
        request.setAttribute("appVersionList",appVersionList);
        return "developer/appinfoview";
    }

    @RequestMapping("/categorylevellist")
    @ResponseBody
    public String categoryLevelList(@RequestParam Integer pid){
        List<AppCategory> categoryLevelList = appCategoryService.findCategoryLevelList(pid);
        return JSON.toJSONString(categoryLevelList);
    }

    @RequestMapping("/list")
    public String appList(@ModelAttribute AppSearchVo vo, HttpServletRequest request){
        vo.setPageIndex(vo.getPageIndex() == null ? 1 : vo.getPageIndex());
        vo.setPageSize(5);

        PageBean<AppInfo> pages = appInfoService.findPage(vo);

        // 状态列表查询
        List<DataDictionary> statusList = dataDictionaryService.findStatusList("APP_STATUS");
        // 所属平台列表查询
        List<DataDictionary> flatFormList =  dataDictionaryService.findFlatFormList("APP_FLATFORM");


        // 查询以及分类 categoryLevel1List
        List<AppCategory> categoryLevel1List = appCategoryService.findCategoryLevelList(null);
        // 在有一级分类的情况下 查询二级分类
        if (categoryLevel1List != null){
            List<AppCategory> categoryLevel2List = appCategoryService.findCategoryLevelList(vo.getQueryCategoryLevel1());
            // 在有二级分类的情况下 查询三级分类
            if (categoryLevel2List != null){
                List<AppCategory> categoryLevel3List = appCategoryService.findCategoryLevelList(vo.getQueryCategoryLevel2());
                request.setAttribute("categoryLevel3List",categoryLevel3List);
            }
            request.setAttribute("categoryLevel2List",categoryLevel2List);

        }

        request.setAttribute("categoryLevel1List",categoryLevel1List);
        request.setAttribute("statusList",statusList);
        request.setAttribute("flatFormList",flatFormList);
        request.setAttribute("pages",pages);

        // 回显
        request.setAttribute("vo",vo);
        return  "developer/appinfolist";
    }

    // 删除app
    @RequestMapping("/delapp")
    @ResponseBody
    public Object delApp(Integer id) {
        Map<String, String> map = new HashMap<>();

        AppInfo appInfo = appInfoService.getAppById(id);
        if (appInfo == null) {
            map.put("delResult", "notexist");
            return map;
        }

        int count = 0;
        try {
            count = appInfoService.delApp(id);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }


        if (count == 0) {
            map.put("delResult", "false");
        } else {
            map.put("delResult", "true");
        }

        return map;
    }

    // 上架与下架
    @RequestMapping("/sale/{appId}/{statusapp}")
    @ResponseBody
    public Object onAndOff(@PathVariable Integer appId, @PathVariable Integer statusapp) {
        Map<String, String> map = new HashMap<>();
        map.put("errorCode", "0");
        int count = appInfoService.onAndOff(appId, statusapp);

        if (count == 0) {
            map.put("resultMsg", "failed");
        } else {
            map.put("resultMsg", "success");
        }

        return map;
    }

    // 跳转到修改appinfo页面
    @RequestMapping("/toupdateappbyid")
    public String toUpdateAppById(HttpServletRequest request, Integer id) {

        AppInfo appInfo = appInfoService.getAppById(id);
        request.setAttribute("appInfo", appInfo);

        return "/developer/appinfomodify";
    }

    // 在修改页面中删除apk或者图片
    @RequestMapping("/delfile")
    @ResponseBody
    public Object delFile(HttpServletRequest request, Integer id, String flag) {
        Map map = new HashMap();
        int count = 0;

        if ("apk".equals(flag)) {
            count = appVersionService.delFile(id);
        } else {
            count = appInfoService.delFile(id);
        }

        if (count == 0) {
            map.put("result", "failed");
        } else {
            map.put("result", "success");
        }
        return map;
    }

    // 根据Id修改app
    @RequestMapping("/updateappbyid")
    public String updateAppById(HttpServletRequest request, AppInfo appInfo,  @RequestParam("attach") MultipartFile multipartFile) {

        String idPicPath = "";
        if (multipartFile != null){
            // 开启文件上传操作
            // 1.定义上传路径    获取上下文的绝对路径
            String filePath = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"fileUpload");
            // 2.获取原文件名
            String filename = multipartFile.getOriginalFilename();
            if (!"".equals(filename)) {
                // 3.获取文件大小
                long size = multipartFile.getSize();
                // 4.获取后缀
                String extension = FilenameUtils.getExtension(filename);
                List<String> list = Arrays.asList("jpg","png","jpeg");
                if (!list.contains(extension.toLowerCase())){ // toLowerCase 将字符串全部变成小写
                    request.setAttribute("idPicPathError","对不起,暂时只支持,jpg,png,jpeg 类型的图片");
                    return "useradd";
                }else if (size > 10485760){
                    request.setAttribute("idPicPathError","文件超出上传大小");
                    return "useradd";
                }else{
                    // 当前系统时间戳  +  随机数  + _Personal.jpg  -> uuid
                    String newFileName = UUID.randomUUID()+"_Personal."+extension;
                    // 核心功能 开始文件上传
                    File file = new File(filePath,newFileName);
                    if (!file.exists()){
                        file.mkdirs();// 创建目录
                    }
                    try {
                        multipartFile.transferTo(file);  // 核心上传功能
                        // 保存上传地址  "statics/fileUpload/newFileName"  相对地址
                        idPicPath = "statics"+File.separator+"fileUpload"+File.separator+newFileName;
                        // System.out.println(idPicPath);
                        // user.setIdPicPath(idPicPath);
                        appInfo.setLogoPicPath(request.getContextPath() + "\\" + idPicPath);
                        appInfo.setLogoLocPath(filePath + "\\" + newFileName);
                    }catch (Exception e){
                        e.printStackTrace();
                        request.setAttribute("idPicPathError","文件上传异常,请重试!");
                    }
                }
            }

        }

        DevUser user = (DevUser) request.getSession().getAttribute("devUserSession");
        appInfo.setModifyBy(user.getId());
        appInfo.setModifyDate(new Date());


        int count = appInfoService.updateAppById(appInfo);

        if (count != 0) {
            return "redirect:/dev/flatform/app/list";
        }

        return "redirect:/dev/flatform/app/toupdateappbyid?id=" + appInfo.getId();

    }
    // 跳转到添加app页面
    @RequestMapping("/toappinfoadd")
    public String toAppInfoAdd() {
        return "/developer/appinfoadd";
    }

    // 添加app信息
    @RequestMapping("/appinfoaddsave")
    public String appInfoAdd(HttpServletRequest request, AppInfo appInfo,  @RequestParam("a_logoPicPath") MultipartFile multipartFile) {

        String idPicPath = "";
        if (multipartFile != null){
            // 开启文件上传操作
            // 1.定义上传路径    获取上下文的绝对路径
            String filePath = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"fileUpload");
            // 2.获取原文件名
            String filename = multipartFile.getOriginalFilename();
            // 3.获取文件大小
            long size = multipartFile.getSize();
            // 4.获取后缀
            String extension = FilenameUtils.getExtension(filename);
            List<String> list = Arrays.asList("jpg","png","jpeg");
            if (!list.contains(extension.toLowerCase())){ // toLowerCase 将字符串全部变成小写
                request.setAttribute("idPicPathError","对不起,暂时只支持,jpg,png,jpeg 类型的图片");
                return "appinfoadd";
            }else if (size > 10485760){
                request.setAttribute("idPicPathError","文件超出上传大小");
                return "appinfoadd";
            }else{
                // 当前系统时间戳  +  随机数  + _Personal.jpg  -> uuid
                String newFileName = UUID.randomUUID()+"_Personal."+extension;
                // 核心功能 开始文件上传
                File file = new File(filePath,newFileName);
                if (!file.exists()){
                    file.mkdirs();// 创建目录
                }
                try {
                    multipartFile.transferTo(file);  // 核心上传功能
                    // 保存上传地址  "statics/fileUpload/newFileName"  相对地址
                    idPicPath = "statics"+File.separator+"fileUpload"+File.separator+newFileName;
                    // System.out.println(idPicPath);
                    // user.setIdPicPath(idPicPath);
                    appInfo.setLogoPicPath(request.getContextPath() + "\\" + idPicPath);
                    appInfo.setLogoLocPath(filePath + "\\" + newFileName);
                }catch (Exception e){
                    e.printStackTrace();
                    request.setAttribute("idPicPathError","文件上传异常,请重试!");
                }
            }
        }

        DevUser user = (DevUser) request.getSession().getAttribute("devUserSession");
        appInfo.setCreatedBy(user.getId());
        appInfo.setDevId(user.getId());
        appInfo.setCreationDate(new Date());


        int count = appInfoService.appInfoAdd(appInfo);

        if (count != 0) {
            return "redirect:/dev/flatform/app/list";
        }


        return "/developer/appinfoadd";
    }
    @RequestMapping("/datadictionarylist")
    @ResponseBody
    public Object getDataDictionaryList(String tcode) {
        return dataDictionaryService.getDictionaryByTypeCode(tcode);
    }

    // 查询appinfo中的apk名字是否存在
    @RequestMapping("/apkexist")
    @ResponseBody
    public Object apkExist(String APKName) {
        Map<String, String> map = new HashMap<>();
        if (EmptyUtils.isEmpty(APKName)) {
            map.put("APKName", "empty");
            return map;
        }

        int count = appInfoService.selectAPKName(APKName);
        if (count == 0) {
            map.put("APKName", "noexist");
        } else {
            map.put("APKName", "exist");
        }

        return map;
    }
}
